<?php

class Account_IndexController extends Zend_Controller_Action
{
	private $_object;

	public function init()
	{
		$this->_object = new Admin_Model_Account ();
	}

	public function indexAction()
	{
		//tham so
		$account_status = $this->_request->getParam ( "account_status", "" );
		$search_keyword = $this->_request->getParam ( "search_keyword", "" );
		
		//tao cau query
		$where = "SELECT tbl_account.*,group_code,group_name FROM tbl_account LEFT JOIN tbl_group ON group_code=account_group_code WHERE 1 ";
		if ($account_status != "")
			$where .= " AND account_status='$account_status'";
		if ($search_keyword != "")
			$where .= " AND (
			account_fullname LIKE '%$search_keyword%' 
			OR account_phone LIKE '%$search_keyword%' 
			OR account_address LIKE '%$search_keyword%'
			OR account_username LIKE '%$search_keyword%'
			) ";
		
		//sap thu tu
		$array_order = $this->_helper->common->getOrderString ( array ("account_username ASC" ),array("group_code ASC") );
		$where.=$array_order;
		
		//lay du lieu
		$data=$this->_object->queryBase ( $where );
		$paginator = Zend_Paginator::factory ( $data );
		$paginator->setCurrentPageNumber ( $this->_request->getParam ( 'page' ) );
		
		//truyen view
		$this->view->paginator = $paginator;
		$this->view->account_status = $account_status;
		$this->view->search_keyword = $search_keyword;
		
		//load files JS/CSS...	
		//$this->view->headScript ()->appendFile ( JS . "autocomplete/main.css" );
		//$this->view->headScript ()->appendFile ( JS . "autocomplete/jquery.autocomplete.css" );
		//$this->view->headScript ()->appendFile ( JS . "autocomplete/jquery.bgiframe.min.js" );
		//$this->view->headScript ()->appendFile ( JS . "autocomplete/jquery.autocomplete.js" );		
	}

	public function publishAction()
	{
		$this->_helper->action->publish ( $this->_object, 'account_status' );
	}

	//luu thong tin dang nhap vao session: gom thong tin ve tai khoan va nhom tai khoan
	private function writeStorage($auth, $adapter)
	{
		//lay thong tin tai khoan
		$object = $adapter->getResultRowObject ();
		
		//lay thong tin nhom tai khoan
		$group = new Admin_Model_Group ();
		$group->group_code = $object->account_group_code;
		$group->fetchRowBase ();
		foreach ( $group->toArray () as $key => $value )
			$object->$key = $group->$key;
		
		//ghi vao session
		$storage = $auth->getStorage ();
		$storage->write ( $object );
		return $storage;
	}

	//hiển thị khi chưa được cấp quyền
	public function noPermissionAction()
	{
		//tham so
		$request=$this->_request;
		$url=$request->getParam('url');
		
		//layout 
		$this->_helper->layout()->setLayout('ajax');
		
		//lấy thông tin của tính năng
		$action = $this->_helper->action->getAction ($url);
		
		//truyen ra view
		$this->view->action=$action;
	}

	public function loginAction()
	{
		//neu dang nhap roi, dang nhap nua thi chuyen qua trang chu
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ())
			$this->_helper->redirector ( "index", "index", "admin", array () );
			
		//layout 
		$this->_helper->layout()->setLayout('login');
		
		//nhận tham số
		$request = $this->_request;
		$login = $request->getParam ( "login", "" );
		$username = $request->getParam ( 'username' );
		$password = $request->getParam ( 'password' );
		
		//tạo form
		if ($login != "")
		{
			$adapter = new Zend_Auth_Adapter_DbTable ( null, 'tbl_account', 'account_username', 'account_password', "MD5(?) AND account_status='1'" );
			$adapter->setIdentity ( $username );
			$adapter->setCredential ( $password );
			$auth = Zend_Auth::getInstance ();
			$result = $auth->authenticate ( $adapter );
			switch ($result->getCode ())
			{
				case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND :
					/** do stuff for nonexistent identity **/
					$this->_helper->flashMessenger->addMessage ( "Tài khoản không tồn tại" );
					break;
				case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID :
					/** do stuff for invalid credential **/
					$account_status = $this->_object->fetchOneBase ( "account_status", "account_username='$username'" );
					if ($account_status == "1")
						$this->_helper->flashMessenger->addMessage ( "Mật khẩu không chính xác" );
					else
						$this->_helper->flashMessenger->addMessage ( "Tài khoản chưa được kích hoạt" );
					break;
				case Zend_Auth_Result::SUCCESS :
					/** do stuff for successful authentication **/
					$storage = $this->writeStorage ( $auth, $adapter );
					$this->_helper->flashMessenger->addMessage ( 'Đăng nhập thành công' );
					if ($_SERVER [HTTP_REFERER] != "")
						$this->_redirect ( $_SERVER [HTTP_REFERER] );
					else
						$this->_helper->redirector ( "index", "index", "admin", array () );
					break;
				default :
					/** do stuff for other failure **/
					$this->_helper->flashMessenger->addMessage ( "Đăng nhập không thành công" );
					break;
			}
			$this->_helper->redirector ( 'login', 'index', 'account', array () );
		}
	}

	public function logoutAction()
	{
		session_destroy ();
		$this->_helper->redirector ( 'login' );
	}

	public function insertAction()
	{
		//lay tham so 
		$request = $this->getRequest ();
		$adminAction = $request->getParam ( 'adminAction' );
		
		//tao form
		$form = new Account_Form_Account_Insert ( $this );
		
		//xu li
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				if ($form->getValue ( 'account_repassword' ) != $form->getValue ( 'account_password' ))
				{
					$form->getElement ( "account_repassword" )->addError ( "Mật khẩu không trùng khớp" );
					$form->markAsError ();
				}
				if (! $form->isErrors ())
				{
					$account = new Admin_Model_Account ( $form->getValues () );
					$account->account_password = md5 ( $account->account_password );
					$account->insertBase ();
					$this->_helper->flashMessenger ( "Thêm tài khoản thành công" );
					if ($adminAction == 'save-and-close')
					{
						$this->_helper->redirector ( 'index', 'index', 'account', array () );
					}
					else if ($adminAction == 'save-and-new')
					{
						$this->_helper->redirector ( 'insert', 'index', 'account', array () );
					}
				}
			}
		}
		
		//gan tham so cho view
		$this->view->form = $form;
	}

	public function updateAction()
	{
		//lay tham so 
		$request = $this->getRequest ();
		$adminAction = $request->getParam ( 'adminAction' );
		$id = $request->getParam ( 'id' );
		if(is_array($id))
			$id=$id[count($id)-1];
		
		//lay doi tuong can cap nhat
		$first_account=new Admin_Model_Account();
		$first_account->findBase ( $id );
		
		//tao form
		$form = new Account_Form_Account_Update ( $this);
		
		//xu li
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				if ($form->getValue ( 'account_repassword' ) != $form->getValue ( 'account_password' ))
				{
					$form->getElement ( "account_repassword" )->addError ( "Mật khẩu không trùng khớp" );
					$form->markAsError ();
				}
				if (! $form->isErrors ())
				{
					$account = new Admin_Model_Account ( $form->getValues () );
					$account->updateBase($id);
					$this->_helper->flashMessenger ( "Cập nhật tài khoản thành công" );
					if ($adminAction == 'save-and-close')
					{
						$this->_helper->redirector ( 'index', 'index', 'account', array () );
					}
					else if ($adminAction == 'save-and-new')
					{
						$this->_helper->redirector ( 'insert', 'index', 'account', array () );
					}
					else
					{
						$this->_helper->redirector ( 'update', "index", "account", array ("id" => $id ) );
					}
				}
			}
		}
		else
		{
			$form->populate ( $first_account->toArray () );
			$account_district = $first_account->account_district;
			$form->account_birthday_time->setValue($this->view->partial("index/format/time.phtml","admin",array($first_account->account_birthday_time)));
		}
		
		//gan tham so cho view
		$this->view->form = $form;
		$this->view->account_district = $account_district;
	}
	
		//Detail
	public function detailAction()
	{
		//lay tham so 
		$request = $this->getRequest ();
		$id = $request->getParam ( 'id' );
		
		//lay doi tuong can cap nhat
		$this->_object->findBase ( $id );
		
		//tao form
		$form = new Account_Form_Account_Detail ( $this );		

		$account = $this->_object;
		
		$account->account_birthday_time = date('d / m / Y', $account->account_birthday_time);
		$account->account_title = Zend_Registry::get('account')->account_title->{$account->account_title};
		$account->account_nation = Zend_Registry::get ( 'account' )->account_nation->{$account->account_nation};
		$account->account_city = Zend_Registry::get ( 'account' )->account_city->{$account->account_city};
		$account->account_district = Zend_Registry::get ( 'account' )->account_district->{$account->account_district};
		
		$form->populate ( $account->toArray () );
		
		//gan tham so cho view
		$this->view->form = $form;
		$this->view->account_district = $account->account_district;
	}
	
	public function profileAction()
	{
		$request = $this->getRequest ();
		$id = Zend_Registry::get('auth')->account_id;
		$this->_forward("detail","index","account",array("id"=>$id));
	}	

	public function assignAction()
	{
		//lay tham so 
		$request = $this->getRequest ();
		$adminAction = $request->getParam ( 'adminAction' );
		$id = $request->getParam ( 'id' );
		
		//lay doi tuong can cap nhat
		$this->_object->findBase ( $id );
		
		//tao form
		$form = new Account_Form_Account_Assign ( $this );
		$group=new Admin_Model_Group();
		$object_arr = array (
			"" => "- Chọn -" 
		) + $group->fetchOptions ( $group->fetchGroups () );
		$form->getElement ( "account_group_code" )->setMultiOptions ( $object_arr );		
		
		//xu li
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				$account = new Admin_Model_Account ( $form->getValues () );
				$account->updateBase ( $id );
				$this->_helper->flashMessenger ( "Phân quyền cho tài khoản thành công" );				
				if ($adminAction == "apply")
					$this->_helper->redirector ( "assign", "index", "account", array ("id" => $id ) );
				else
					$this->_helper->redirector ( "index" , "index", "account",array());
			}
		}
		else
		{
			$form->populate ( $this->_object->toArray () );
		}
		
		//gan tham so cho view
		$this->view->form = $form;
		$this->view->account_district = $account_district;
	}

	//hàm kiểm tra dữ liệu ràng buộc trước khi xóa
	//nếu trả về true thì cho xóa, ngược lại kg cho xóa
	public function beforeDelete()
	{
		$request = Zend_Controller_Front::getInstance ()->getRequest ();
		$ids = (array)$request->getParam ( 'id');
		$msg="";
		foreach ($ids as $id)
		{
			//lay san pham
			$account = new Admin_Model_Account();
			$account->findBase ( $id );

			//Kiem tra xem co phieu xuat kho ghi chú
			$inbound = new Admin_Model_TmpInbound ();
			if ($inbound->fetchRowAllBase ( "inbound_warehouse_keep_user = '{$account->account_username}' OR  inbound_create_user = '{$account->account_username}' " ) !== FALSE)
			{
				$msg .= " - Phiếu xuất kho (ghi chú) có mã số: <strong>{$inbound->inbound_code}</strong>";
				break;
			}
			
		    //Kiem tra xem co phieu nhập xuat kho
			$inbound = new Admin_Model_Inbound ();
			if ($inbound->fetchRowAllBase ( "inbound_warehouse_keep_user = '{$account->account_username}' OR  inbound_create_user = '{$account->account_username}' " ) !== FALSE)
			{
				$msg .= " - Phiếu nhập/xuất kho có mã số: <strong>{$inbound->inbound_code}</strong>";
				break;
			}
		}				
		if($msg!="")
		{
			$msg = "Dữ liệu này đã có trong:<br />".$msg;
			$this->_helper->flashMessenger ( $msg );
			return false;
		}
		return true;
	}
	
	public function afterDelete()
	{
		
	}

	public function deleteAction()
	{
		$this->_helper->action->delete ( $this->_object, "afterDelete", "beforeDelete" );
	}	

	public function ajaxLoadDistrictAction()
	{
		$this->_helper->layout ()->disableLayout ();
		$account_city = $this->_request->getParam ( "account_city" );
		$account_district = $this->_request->getParam ( "account_district" );
		$array = array ();
		if ($account_city != "")
			$array = Zend_Registry::get ( "account" )->account_district->$account_city->toArray ();
		$this->view->array = $array;
		$this->view->account_district = $account_district;
	}

	public function updatePasswordAction()
	{
		//lay tham so 
		$request = $this->getRequest ();
		$id = $request->getParam ( "id" );
		
		//lay tai khoan can cap nhat
		$this->_object->findBase ( $id );
		
		//tao form
		$form = new Account_Form_Account_UpdatePassword ( $this, $this->_object );
		
		//xu li
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				if ($form->getValue ( 'account_repassword' ) != $form->getValue ( 'account_password' ))
				{
					$form->getElement ( "account_repassword" )->addError ( "Mật khẩu mới không trùng khớp" );
					$form->markAsError ();
				}
				if (! $form->isErrors ())
				{
					$account = new Admin_Model_Account ( $form->getValues () );
					$account->account_password = md5 ( $account->account_password );
					$account->updateBase ( $id );
					$this->_helper->flashMessenger ( "Đổi mật khẩu thành công" );
					return $this->_helper->redirector ( 'index', 'index', 'account', array () );
				}
			}
		}
		
		//gan tham so cho view
		$this->view->form = $form;
	}
	
	public function changePasswordAction()
	{
		//lay tham so 
		$request = $this->getRequest ();
		$id=Zend_Registry::get('auth')->account_id;
		$this->_forward("update-password","index","account",array("id"=>$id));
	}
}

